package com.example.translateappjava.Activity.HomeFragmentActivity.Forum;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout; // ****** Import LinearLayout ******
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.translateappjava.Adapter.PostAdapter;
import com.example.translateappjava.Adapter.SearchHistoryAdapter;
import com.example.translateappjava.R;
import com.example.translateappjava.Repository.PostRepository;
import com.example.translateappjava.Utils.Post;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ForumSearchActivity extends AppCompatActivity implements PostAdapter.OnPostClickListener, SearchHistoryAdapter.OnSearchHistoryClickListener {

    private static final String TAG = "ForumSearchActivity";
    private static final String PREFS_NAME = "ForumSearchPrefs";
    private static final String SEARCH_HISTORY_KEY = "SearchHistory";

    private EditText etSearch;
    private RecyclerView rvSearchResults;
    private TextView tvSearchHistoryTitle;
    private RecyclerView rvSearchHistory;
    private View layoutNoResultsContainer;
    private TextView tvNoResultsMessage;
    private View recommendsLayout;
    private View layoutSearchSuggestions; // ****** 新增，用于引用搜索建议的LinearLayout ******

    private PostAdapter searchResultAdapter;
    private SearchHistoryAdapter searchHistoryAdapter;

    private List<Post> allPostsForSearch = new ArrayList<>();
    private List<Post> searchResultsList = new ArrayList<>();
    private List<String> searchHistoryList = new ArrayList<>();

    private String currentSearchQuery = "";
    private PostRepository postRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_search);

        postRepository = new PostRepository(getApplication());

        setupToolbar();
        initViews();
        // ****** 在initViews之后，设置建议项的点击事件 ******
        setupSuggestionClickListeners();
        initDataAndLoadPosts();
        setupRecyclerViews();
        setupSearchListener();

        // 初始状态由 initDataAndLoadPosts 的回调或 TextWatcher 处理
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("搜索帖子");
        }
    }

    private void initViews() {
        etSearch = findViewById(R.id.et_search);
        rvSearchResults = findViewById(R.id.rv_search_results);
        layoutNoResultsContainer = findViewById(R.id.layout_no_results_container);
        tvNoResultsMessage = findViewById(R.id.tv_no_results_message);
        tvSearchHistoryTitle = findViewById(R.id.tv_search_history);
        rvSearchHistory = findViewById(R.id.rv_search_history);
        recommendsLayout = findViewById(R.id.recommends);
        layoutSearchSuggestions = findViewById(R.id.layout_search_suggestions); // ****** 初始化 ******
    }

    // ****** 新增方法：为搜索建议项设置点击事件 ******
    private void setupSuggestionClickListeners() {
        View.OnClickListener suggestionClickListener = v -> {
            if (v instanceof TextView) {
                String query = ((TextView) v).getText().toString();
                etSearch.setText(query);
                etSearch.setSelection(query.length()); // 光标移到末尾
                // TextWatcher会监听到变化并执行搜索
            }
        };

        findViewById(R.id.hot_search_1).setOnClickListener(suggestionClickListener);
        findViewById(R.id.hot_search_2).setOnClickListener(suggestionClickListener);
        findViewById(R.id.category_search_1).setOnClickListener(suggestionClickListener);
        findViewById(R.id.category_search_2).setOnClickListener(suggestionClickListener);
        findViewById(R.id.category_search_3).setOnClickListener(suggestionClickListener);
        findViewById(R.id.category_search_4).setOnClickListener(suggestionClickListener);
    }


    private void initDataAndLoadPosts() {
        loadSearchHistory();

        Log.d(TAG, "Loading posts from DB for search...");
        postRepository.getAllPosts(new PostRepository.RepositoryCallback<List<Post>>() {
            @Override
            public void onSuccess(List<Post> postsFromDb) {
                if (!isFinishing() && !isDestroyed()) {
                    Log.d(TAG, "Loaded " + (postsFromDb != null ? postsFromDb.size() : 0) + " posts from DB for search.");
                    allPostsForSearch.clear();
                    if (postsFromDb != null) {
                        allPostsForSearch.addAll(postsFromDb);
                    }

                    String initialQuery = etSearch.getText().toString().trim();
                    if (!TextUtils.isEmpty(initialQuery)) {
                        performSearch(initialQuery);
                    } else {
                        showSearchHistoryOrRecommendations();
                    }

                    if (allPostsForSearch.isEmpty() && TextUtils.isEmpty(initialQuery)) {
                        Toast.makeText(ForumSearchActivity.this, "本地暂无帖子数据可供搜索", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onError(Exception e) {
                if (!isFinishing() && !isDestroyed()) {
                    Log.e(TAG, "Error loading posts from DB for search", e);
                    Toast.makeText(ForumSearchActivity.this, "加载帖子数据失败", Toast.LENGTH_SHORT).show();
                    showSearchHistoryOrRecommendations();
                }
            }
        });
    }


    private void setupRecyclerViews() {
        searchResultAdapter = new PostAdapter(searchResultsList, this);
        rvSearchResults.setLayoutManager(new LinearLayoutManager(this));
        rvSearchResults.setAdapter(searchResultAdapter);

        searchHistoryAdapter = new SearchHistoryAdapter(this, searchHistoryList);
        rvSearchHistory.setLayoutManager(new LinearLayoutManager(this));
        rvSearchHistory.setAdapter(searchHistoryAdapter);
    }

    private void setupSearchListener() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentSearchQuery = s.toString().trim();
                if (TextUtils.isEmpty(currentSearchQuery)) {
                    searchResultsList.clear();
                    if(searchResultAdapter != null) searchResultAdapter.notifyDataSetChanged();
                    showSearchHistoryOrRecommendations();
                } else {
                    performSearch(currentSearchQuery);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void performSearch(String query) {
        hideSearchHistoryAndRecommendations(); // ****** 搜索时隐藏历史和建议 ******

        searchResultsList.clear();

        if (TextUtils.isEmpty(query) || allPostsForSearch.isEmpty()) {
            updateSearchResultsUI();
            return;
        }

        // 将搜索词添加到历史记录（在执行搜索前或后都可以，这里放在前面）
        addToSearchHistory(query);


        String lowerCaseQuery = query.toLowerCase();
        for (Post post : allPostsForSearch) {
            boolean titleMatch = post.getTitle() != null && post.getTitle().toLowerCase().contains(lowerCaseQuery);
            boolean contentMatch = post.getContent() != null && post.getContent().toLowerCase().contains(lowerCaseQuery);
            boolean categoryMatch = post.getCategory() != null && post.getCategory().toLowerCase().contains(lowerCaseQuery);
            boolean usernameMatch = post.getUsername() != null && post.getUsername().toLowerCase().contains(lowerCaseQuery);

            if (titleMatch || contentMatch || categoryMatch || usernameMatch) {
                searchResultsList.add(post);
            }
        }
        updateSearchResultsUI();
    }

    private void updateSearchResultsUI() {
        if (!searchResultsList.isEmpty()) {
            rvSearchResults.setVisibility(View.VISIBLE);
            layoutNoResultsContainer.setVisibility(View.GONE);
        } else if (!TextUtils.isEmpty(currentSearchQuery)) { // 确保是有搜索词但无结果
            rvSearchResults.setVisibility(View.GONE);
            layoutNoResultsContainer.setVisibility(View.VISIBLE);
            tvNoResultsMessage.setText("未找到包含 \"" + currentSearchQuery + "\" 的帖子");
        } else { // 搜索词为空，此时应该显示历史和建议，由 TextWatcher -> showSearchHistoryOrRecommendations 处理
            rvSearchResults.setVisibility(View.GONE);
            layoutNoResultsContainer.setVisibility(View.GONE);
        }
        if(searchResultAdapter != null) searchResultAdapter.notifyDataSetChanged();
    }

    // ****** 修改此方法逻辑 ******
    private void showSearchHistoryOrRecommendations() {
        rvSearchResults.setVisibility(View.GONE);
        layoutNoResultsContainer.setVisibility(View.GONE);

        boolean hasHistory = searchHistoryList != null && !searchHistoryList.isEmpty();

        // 1. 显示 recommends 父布局
        if (recommendsLayout != null) {
            recommendsLayout.setVisibility(View.VISIBLE);
        }

        // 2. 控制搜索历史部分的可见性
        if (tvSearchHistoryTitle != null) {
            tvSearchHistoryTitle.setVisibility(hasHistory ? View.VISIBLE : View.GONE);
        }
        if (rvSearchHistory != null) {
            rvSearchHistory.setVisibility(hasHistory ? View.VISIBLE : View.GONE);
        }

        // 3. 确保搜索建议部分可见，并调整其 marginTop
        if (layoutSearchSuggestions != null) {
            layoutSearchSuggestions.setVisibility(View.VISIBLE); // 确保建议区域可见

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutSearchSuggestions.getLayoutParams();
            if (hasHistory) {
                // 如果有历史记录，使用XML中定义的marginTop (e.g., 32dp)
                // 你可以将这个值定义在 dimens.xml 中，然后通过 getResources().getDimensionPixelSize() 获取
                params.topMargin = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics());
            } else {
                // 如果没有历史记录，可以将marginTop减小，比如设置为一个较小的值或0，让建议区更靠近顶部
                params.topMargin = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()); // 例如，8dp
            }
            layoutSearchSuggestions.setLayoutParams(params);
        }

        if(searchHistoryAdapter != null) searchHistoryAdapter.notifyDataSetChanged();
        Log.d(TAG, "Showing search history and/or recommendations. Has history: " + hasHistory);
    }

    // ****** 修改此方法逻辑 ******
    private void hideSearchHistoryAndRecommendations() {
        if (recommendsLayout != null) {
            recommendsLayout.setVisibility(View.GONE);
        }
        // 子View（历史标题、历史列表、建议布局）会随父布局隐藏，无需单独设置
        Log.d(TAG, "Hiding recommends layout (history and suggestions).");
    }


    private void addToSearchHistory(String query) {
        if (TextUtils.isEmpty(query)) return;
        query = query.trim();
        if (searchHistoryList == null) searchHistoryList = new ArrayList<>();

        searchHistoryList.remove(query);
        searchHistoryList.add(0, query);

        while (searchHistoryList.size() > 10) {
            searchHistoryList.remove(searchHistoryList.size() - 1);
        }
        saveSearchHistory();
        // 当历史记录更新时，如果当前显示的是历史/建议区，则刷新UI
        if (recommendsLayout != null && recommendsLayout.getVisibility() == View.VISIBLE) {
            if (searchHistoryAdapter != null) searchHistoryAdapter.notifyDataSetChanged();
            // 重新调整建议区的marginTop，因为历史记录状态可能已改变
            boolean hasHistory = !searchHistoryList.isEmpty();
            if (layoutSearchSuggestions != null) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutSearchSuggestions.getLayoutParams();
                if (hasHistory) {
                    params.topMargin = (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 32, getResources().getDisplayMetrics());
                } else {
                    params.topMargin = (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
                }
                layoutSearchSuggestions.setLayoutParams(params);
            }
            // 如果添加历史后，历史标题应该显示
            if(tvSearchHistoryTitle != null) tvSearchHistoryTitle.setVisibility(hasHistory ? View.VISIBLE : View.GONE);
            if(rvSearchHistory != null) rvSearchHistory.setVisibility(hasHistory ? View.VISIBLE : View.GONE);
        }
    }

    private void loadSearchHistory() {
        if (searchHistoryList == null) searchHistoryList = new ArrayList<>();
        else searchHistoryList.clear();

        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String jsonHistory = prefs.getString(SEARCH_HISTORY_KEY, null);
        if (jsonHistory != null) {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            List<String> loadedHistory = gson.fromJson(jsonHistory, type);
            if (loadedHistory != null) {
                searchHistoryList.addAll(loadedHistory);
            }
        }
        Log.d(TAG, "Loaded search history count: " + searchHistoryList.size());
    }

    private void saveSearchHistory() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String jsonHistory = gson.toJson(searchHistoryList);
        editor.putString(SEARCH_HISTORY_KEY, jsonHistory);
        editor.apply();
        Log.d(TAG, "Saved search history count: " + searchHistoryList.size());
    }

    @Override
    public void onPostClick(Post post) {
        // 在这里，点击搜索结果项时，应该将当前搜索框的文本（如果非空）加入历史
        String currentQueryInBox = etSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(currentQueryInBox)) {
            addToSearchHistory(currentQueryInBox); // 将搜索框内的词加入历史
        }
        // （原有的将post.getTitle()加入历史的逻辑可以移除或保留，取决于你的产品需求）
        // else if (post.getTitle() != null && !post.getTitle().isEmpty()) {
        //     addToSearchHistory(post.getTitle());
        // }

        Intent intent = new Intent(this, PostDetailActivity.class);
        if (post != null && post.getServerId() != null) {
            intent.putExtra("post_id", post.getServerId());
            Log.d(TAG, "Search: Passing serverId to PostDetailActivity: " + post.getServerId());
        } else {
            Log.w(TAG, "Search: post or serverId is null for clicked post.");
        }
        intent.putExtra("post_title", post != null ? post.getTitle() : "未知标题");
        intent.putExtra("post_content", post != null ? post.getContent() : "未知内容");
        intent.putExtra("post_username", post != null ? post.getUsername() : "未知作者");
        intent.putExtra("post_time", post != null ? post.getTime() : "未知时间");
        intent.putExtra("post_category", post != null ? post.getCategory() : "未知分类");
        intent.putExtra("post_like_count", post != null ? post.getLikeCount() : 0);
        intent.putExtra("post_comment_count", post != null ? post.getCommentCount() : 0);
        intent.putExtra("post_avatar_url", post != null ? post.getAvatarUrl() : null);
        startActivity(intent);
    }

    @Override
    public void onSearchHistoryClick(String historyItem) {
        if (historyItem != null) {
            etSearch.setText(historyItem);
            etSearch.setSelection(historyItem.length());
            // TextWatcher 会自动调用 performSearch(historyItem)
            // 并且 performSearch 内部会调用 addToSearchHistory, 将点击的历史项再次置顶
        }
    }

    public void clearSearchHistory(View view) {
        searchHistoryList.clear();
        saveSearchHistory();
        // 更新UI，因为历史记录已空，建议区的marginTop可能需要调整
        showSearchHistoryOrRecommendations();
        Toast.makeText(this, "搜索历史已清除", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}